<?php

/**
 * This is the model class for table "b2b_external_user".
 *
 * The followings are the available columns in table 'b2b_external_user':
 * @property integer $id
 * @property string $realname
 * @property integer $customer_certificate
 * @property string $customer_no
 * @property integer $company_id
 * @property string $company_name
 * @property string $level
 * @property integer $gender
 * @property integer $married
 */
class B2bExternalUser extends CActiveRecord
{
    //0正常，可预约，1已预约，待确认，2已预约确认，3已体检，4团预约,待确认，5团约，已确认
    const YUYUE_ENABLE = 0; 
    const GEREN_YUYUEING = 1; 
    const GEREN_YUYUED = 2; 
    const TJ_FINISH = 3; 
    const TUAN_YUYUEING = 4; 
    const TUAN_YUYUED = 5; 
    
    const GENDER_GIRL = 2; 
    const GENDER_BOY = 1; 
    const GENDER_UNKNOW = 0; 
    
    const MARRIED_YES = 1; 
    const MARRIED_NO = 0; 
    const MARRIED_UNKNOW = 2; 
    
    

    /**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return B2bExternalUser the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'b2b_external_user';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
				return array(
					array('realname, customer_no, company_id', 'required'),
					array('customer_certificate, company_id, gender, married', 'numerical', 'integerOnly'=>true),
					array('realname', 'length', 'max'=>100),
					array('customer_no', 'length', 'max'=>64),
					array('company_name', 'length', 'max'=>255),
					array('level', 'length', 'max'=>50),
					// The following rule is used by search().
					// Please remove those attributes that should not be searched.
					array('id, realname, customer_certificate, customer_no, telephone,password,email,company_id, company_name, level, gender, married', 'safe', 'on'=>'search'),
				);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
                    'package' => array(self::BELONGS_TO,'B2bPackage',array('package_id'=>'id')),
                    'centers' => array(self::HAS_MANY,'B2bPackageToCenter',array('package_id'=>'package_id')),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'realname' => '真实姓名',
			'customer_certificate' => '证件类型',
			'customer_no' => '证件号',
			'telephone' => '电话',
			'password' => '密码',
			'email' => '电子邮箱',
			'company_id' => '公司ID',
			'company_name' => '企业名称',
			'level' => 'Level',
			'gender' => '性别',
			'married' => '婚否',
			'package_name' => '体检套餐名',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('realname',$this->realname,true);
		$criteria->compare('customer_certificate',$this->customer_certificate);
		$criteria->compare('customer_no',$this->customer_no,true);
		$criteria->compare('company_id',$this->company_id);
		$criteria->compare('company_name',$this->company_name,true);
		$criteria->compare('level',$this->level,true);
		$criteria->compare('gender',$this->gender);
		$criteria->compare('married',$this->married);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
                            'pagination'=>array('pageSize'=>30,
                       ),
		));
	}

	/**
	 * 根据姓名身份证获取相关信息
	 */
	public function getInfos($name,$idcard){
		$criteria=new CDbCriteria;
		//$criteria->select='company_name,company_name';  // 只选择 'title' 列
		$statuscode = 0;
		$criteria->condition='realname=:name and customer_no=:idcard and statuscode=:statuscode';
		$criteria->params=array(':name'=>$name,':idcard'=>$idcard,':statuscode'=>$statuscode);

		$ret = $this->find($criteria);
		//如果找不到，返回的是null，否则返回的是记录
		return $ret;
	}

	/**
	 * 登录的时候，根据登录名（即手机号码）获取用户信息
	 */
	function getLoginInfos($idcard){
		$criteria = new CDbCriteria;
		//            $criteria->select='identity_no';  // 只选择 'title' 列
		$criteria->condition = 'customer_no =:idcard and statuscode=0';
		$criteria->params=array(':idcard'=>$idcard);

		return $this->find($criteria);
	}
	
	/**
	 * 返回最近一次可用的体检信息
	 */
	public function getLastExamination($idcard)
	{
		$criteria = new CDbCriteria;
		$criteria->condition = 'customer_no =:idcard';
		$criteria->order = 't.id desc';
		$criteria->params=array(':idcard'=>$idcard);
		$criteria->with = array("package","centers");
		$ret = $this->findAll($criteria);
		if(empty($ret)){
			return null;
		}
		return $ret[0];
	}
        
        /**
         *  根据公司ID返回所有导入的用户
         */
        public function getCompUser($cid,$status = null){
            $criteria = new CDbCriteria();
            $criteria->compare("company_id", $cid);
            
            if(null !== $status){
                if($status == 1){
                    $criteria->compare("statuscode", array(1,2,4,5));
                }elseif($status == 2){
                    $criteria->compare("statuscode", 3);
                }elseif($status == 3){
                    $criteria->compare("statuscode", array(1,2,3));
                }elseif($status == 0){
                    $criteria->compare("statuscode", 0);
                }
                
            }
            
            return new CActiveDataProvider($this, array(
                'criteria'=>$criteria,
                'pagination'=>array('pageSize'=>30,
               ),
            ));
        }
        
        public function import($users,$company_id,&$importinfo){
            $company = B2bCompany::model()->findByPk($company_id);
            if(null === $company){
                return "错误的公司信息";
            }
            $sql = <<<EOF
INSERT INTO  `marvel`.`b2b_external_user` (
`realname` ,
`customer_certificate` ,
`age` ,
`customer_no` ,
`company_id` ,
`company_name` ,
`package_id` ,
`gender` ,
`married` ,
`statuscode` ,
`create_at` ,
`update_at`
)
VALUES (
:realname,  0,:age,  :customer_no,   $company->id, '$company->name',
:package_id,  :gender, :married ,  0,  NOW( ) , NOW( )
);
EOF;
            $comm = Yii::app()->db->createCommand($sql);
            foreach($users["realname"] as $key=>$u){
                $params["realname"] = $u;
                $params["age"] = $users["age"][$key];
                $params["customer_no"] = $users["idcard_no"][$key];
                $params["package_id"] = $users["package_id"][$key];
                if(trim($users["gender"][$key])=="男"){
                    $params["gender"] = B2bExternalUser::GENDER_BOY;
                }elseif(trim($users["gender"][$key])=="女"){
                    $params["gender"] = B2bExternalUser::GENDER_GIRL;
                }else{
                    $params["gender"] = B2bExternalUser::GENDER_UNKNOW;
                }
                
                if(trim($users["married"][$key])=="已婚"){
                    $params["married"] = B2bExternalUser::MARRIED_YES;
                }elseif(trim($users["married"][$key])=="未婚"){
                    $params["married"] = B2bExternalUser::MARRIED_NO;
                }else{
                    $params["married"] = B2bExternalUser::MARRIED_UNKNOW;
                }
                $ret = $comm->execute($params);
                if($ret == 1){
                    $importinfo["success"]++;
                }else{
                    $importinfo["failed"]++;
                }
            }
            return true;
        }

	/*
	 * 企业用户登录
	 * @param $username  用户名
	 * @param $password   密码
	 * return
	 */
		public function verifyExtUser($username, $password) {
			$ret = $this->findByAttributes(array('telephone'=>$username));
			if ($ret === null) {
				return false;
			}
			if ($ret["password"] !== $password) {
				return false;
			}
			return $ret;
		}
}